package com.cmsz.jiangxm.MyBatisTest.service;

import java.util.List;

//import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.cmsz.jiangxm.MyBatisTest.dao.UserDao;
import com.cmsz.jiangxm.MyBatisTest.model.PageInfo;
import com.cmsz.jiangxm.MyBatisTest.model.User;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

@Service
@Transactional(readOnly=true,rollbackFor=Exception.class)
//@MapperScan("com.cmsz.jiangxm.MyBatisTest.dao")
public class UserService {
	
	@Autowired
    private UserDao userDao;

	@Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.DEFAULT,readOnly=false)
    public int addUser(User user){
        return userDao.insertUser(user);
    }

    public User getUserById(int id){
        return userDao.selectUserById(id);
    }

    public List<User> getAllUsers(){
        return userDao.getAllUsers();
    }
    
    @Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.DEFAULT,readOnly=false)
    public int deleteUserById(int id) {
    	return userDao.deleteUserById(id);
    }
    
    public int updateUser(User user) {
    	return userDao.updateUser(user);
    }
    
    public PageInfo<User> queryByPage(String userName,int pageNum,int pageSize){
    	Page<User> userPage = PageHelper.startPage(pageNum, pageSize);
    	userDao.queryByPage(userName);
    	PageInfo<User> users = new PageInfo<User>(userPage);
    	return users;
    }
    
  //测试事务  
    //注意：方法的@Transactional会覆盖类上面声明的事务  
    //Propagation.REQUIRED ：有事务就处于当前事务中，没事务就创建一个事务  
    //isolation=Isolation.DEFAULT：事务数据库的默认隔离级别  
    @Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.DEFAULT,readOnly=false)  
    public void testTransational(){  
          
        //删除全部  
        this.userDao.deleteAll();  
        //新增  
        User u = new User();  
        u.setId(10);  
        u.setName("张三");
        u.setAge(10);
        u.setSex("female");
        this.userDao.insertUser(u);  
        //制造异常  
        //如果类上面没有@Transactional,方法上也没有，哪怕throw new RuntimeException,数据库也会提交  
        throw new RuntimeException("事务异常测试");  
    }
}
